<!-- src/views/Login.vue -->
<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>登录</h2>
      <el-form :model="loginForm" ref="loginForm" label-width="80px">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
        >
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleLogin" style="width: 100%;">登录</el-button>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  name: 'Login',
  setup() {
    const router = useRouter();
    const loginForm = ref({
      username: '',
      password: '',
    });

    /**
     * 处理登录
     */
    const handleLogin = () => {
      if (!loginForm.value.username || !loginForm.value.password) {
        ElMessage.warning('请填写所有必填项');
        return;
      }

      // console.log('登录请求数据:', loginForm.value); // 调试日志

      axios
        .post('/api/login', loginForm.value)
        .then((response) => {
          // console.log('登录响应:', response.data); // 调试日志
          if (response.data.success) {
            localStorage.setItem('user', JSON.stringify(response.data.user));
            ElMessage.success('登录成功');
            router.push('/dashboard'); // 跳转到仪表盘
          } else {
            ElMessage.error(response.data.message || '登录失败');
          }
        })
        .catch((error) => {
          console.error('登录请求失败:', error);
          ElMessage.error('登录失败，请稍后再试');
        });
    };

    return {
      loginForm,
      handleLogin,
    };
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 400px;
  padding: 20px;
  text-align: center;
}
</style>
